package com.neusoft.controller;

import com.neusoft.model.Admin;
import com.neusoft.service.AdminService;
import com.neusoft.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Author: duan
 * @Date: Create in 19:35 2020/10/19
 */
@WebServlet("/admin")
public class AdminController extends HttpServlet {
    private AdminService adminService = new AdminServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("dopost");
        //中文乱码处理
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String type = req.getParameter("type");
        if("login".equals(type)) {
            login(req, resp);
        } else if("reg".equals(type)) {
            reg(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //登录处理
        System.out.println("登录处理");
        String account = req.getParameter("account");
        String password = req.getParameter("password");

        Admin bean = adminService.getByUsernameAndPassword(account, password);
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        if (bean != null) {
            writer.println("登录成功");
        } else {
            writer.println("登录失败");
        }
    }

    public void reg(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //注册处理
        System.out.println("注册处理");
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        String cfmpassword = req.getParameter("cfmpassword");

        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        if (!password.equals(cfmpassword)) {
            writer.println("注册失败，两次密码不一致");
            return;
        }

        //accout是否重复
        List<Admin> listByUsername = adminService.getListByUsername(account);
        if (listByUsername.size() != 0) {
            writer.println("注册失败，用户名重复");
            return;
        }

        Admin bean = new Admin();
        bean.setId(0L);
        bean.setUsername(account);
        bean.setPassword(password);
        boolean insert = adminService.insert(bean);
        if (insert) {
            writer.println("注册成功");
        } else {
            writer.println("注册失败");
        }
    }
}
